<template>
  <div class="repair-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><Tools /></el-icon>
            <span>报修管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain>
              <el-icon><Plus /></el-icon>添加报修
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0" plain>
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button type="success" @click="handleExport" plain>
              <el-icon><Download /></el-icon>导出Excel
            </el-button>
            <el-button type="warning" @click="handleImport" plain>
              <el-icon><Upload /></el-icon>导入Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/maintenance.png" alt="Repair Management Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>报修管理</h3>
          <p>高效处理业主报修请求，及时解决设施问题，提升服务质量</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属小区">
          <el-select v-model="searchForm.communityId" placeholder="请选择小区" clearable>
            <el-option 
              v-for="item in communities" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报修人">
          <el-input v-model="searchForm.reporter" placeholder="请输入报修人" clearable>
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable>
            <el-option label="待处理" :value="0"></el-option>
            <el-option label="处理中" :value="1"></el-option>
            <el-option label="已完成" :value="2"></el-option>
            <el-option label="已取消" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>报修列表</span>
          <el-tag type="info">共 {{ total }} 条记录</el-tag>
    </div>
      </template>

    <el-table
        v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="'暂无报修数据'"
      >
        <el-table-column type="selection" width="55" fixed="left" />
       
        <el-table-column prop="community" label="所属小区" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><House /></el-icon>
              <span>{{ scope.row.community || '未知小区' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reporter" label="报修人" width="100">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><User /></el-icon>
              <span>{{ scope.row.reporter }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系方式" width="140">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Phone /></el-icon>
              <span>{{ scope.row.contact || '未提供' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="报修地址" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Location /></el-icon>
              <span>{{ scope.row.address }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="报修内容" width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Document /></el-icon>
              <span>{{ scope.row.description }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reportTime" label="报修时间" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Calendar /></el-icon>
              <span>{{ scope.row.reportTime }}</span>
            </div>
          </template>
        </el-table-column>
      <el-table-column prop="status" label="处理状态" width="100">
        <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status !== undefined ? scope.row.statusValue : scope.row.status)" effect="plain">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
            <div class="operation-buttons">
          <el-button
            size="small"
            @click="handleEdit(scope.row)"
            type="primary"
            text
          >
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
            size="small"
            @click="handleDelete(scope.row)"
            type="danger"
            text
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
            </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-box">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
          background
        />
    </div>
    </el-card>

    <!-- 导入Excel对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入Excel" width="500px">
      <div class="import-dialog-content">
        <el-alert
          title="请先下载模板，按照模板格式填写数据后上传"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <div class="template-download">
          <el-button type="primary" @click="downloadTemplate" size="small">
            <el-icon><Download /></el-icon>下载模板
          </el-button>
        </div>
        
        <el-upload
          class="excel-upload"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传xlsx/xls文件</div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importing">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  Plus, 
  Edit, 
  Delete, 
  User, 
  Phone, 
  House, 
  Calendar, 
  Document, 
  Tools,
  Location,
  Search,
  Download,
  Upload
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import ExcelUtil from '@/utils/ExcelUtil';

export default {
  name: 'RepairList',
  components: {
    Plus,
    Edit,
    Delete,
    User,
    Phone,
    House,
    Calendar,
    Document,
    Tools,
    Location,
    Search,
    Download,
    Upload
  },
  data() {
    return {
      searchForm: {
        communityId: '',
        reporter: '',
        status: ''
      },
      tableData: [],
      communities: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      importDialogVisible: false,
      fileList: [],
      importing: false,
      exportLoading: false
    };
  },
  created() {
    this.fetchCommunities();
    this.fetchRepairs();
  },
  methods: {
    // 获取小区列表
    fetchCommunities() {
      axios.get('/api/communities')
        .then(response => {
          this.communities = response.data;
        })
        .catch(error => {
          console.error('获取小区列表失败:', error);
          ElMessage.error('获取小区列表失败');
        });
    },
    
    // 获取维修列表
    fetchRepairs() {
      this.loading = true;
      
      const params = {
        page: this.currentPage - 1,
        size: this.pageSize
      };
      
      // 添加筛选条件
      if (this.searchForm.communityId) {
        params.communityId = this.searchForm.communityId;
      }
      if (this.searchForm.reporter) {
        params.reporter = this.searchForm.reporter;
      }
      if (this.searchForm.status !== '') {
        params.status = this.searchForm.status;
      }
      
      axios.get('/api/repairs', { params })
        .then(response => {
          console.log('API Response:', response.data); // 调试日志
          
          if (response.data && response.data.content) {
            // 分页响应
            this.tableData = response.data.content;
            this.total = response.data.totalItems || response.data.totalElements;
          } else if (Array.isArray(response.data)) {
            // 数组响应
            this.tableData = response.data;
            this.total = response.data.length;
          } else {
            // 其他情况
            this.tableData = [];
            this.total = 0;
          }
          
          // 处理数据，确保字段名一致
          this.tableData.forEach(item => {
            // 确保owner存在且有name属性
            if (item.owner && item.owner.name) {
              item.reporter = item.owner.name;
              
              // 设置联系方式 - 使用phoneNumber属性
              if (item.owner.phoneNumber) {
                item.contact = item.owner.phoneNumber;
              }
            }
            
            // 确保home存在且有相关属性
            if (item.home) {
              // 构建完整地址
              let address = '';
              
              // 添加楼栋信息
              if (item.home.building && item.home.building.name) {
                address += item.home.building.name;
            
                // 设置社区名称 - 从building中获取community
                if (item.home.building.community && item.home.building.community.name) {
                  item.community = item.home.building.community.name;
                }
            }
            
              // 添加房屋名称
              if (item.home.name) {
                address += ' ' + item.home.name;
              }
              
              item.address = address || '未知地址';
            }
            
            // 确保状态显示正确 - 将数字转换为文本
            if (item.status !== undefined) {
              // 保留原始数值用于样式
              item.statusValue = item.status;
              
              // 转换为文本描述
              switch(item.status) {
                case 0:
                  item.status = '待处理';
                  break;
                case 1:
                  item.status = '处理中';
                  break;
                case 2:
                  item.status = '已完成';
                  break;
                case 3:
                  item.status = '已取消';
                  break;
                default:
                  // 如果已经是文本，则不处理
                  if (typeof item.status !== 'string') {
                    item.status = '未知';
                  }
              }
            }
          });
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取报修列表失败:', error);
          ElMessage.error('获取报修列表失败');
          this.tableData = [];
          this.total = 0;
          this.loading = false;
        });
    },
    
    // 搜索报修
    onSearch() {
      this.currentPage = 1;
      this.fetchRepairs();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm.communityId = '';
      this.searchForm.reporter = '';
      this.searchForm.status = '';
      this.currentPage = 1;
      this.fetchRepairs();
    },
    
    // 获取状态类型
    getStatusType(status) {
      switch(status) {
        case 0:
        case '待处理':
          return 'info';
        case 1:
        case '处理中':
          return 'warning';
        case 2:
        case '已完成':
          return 'success';
        case 3:
        case '已取消':
          return 'danger';
        default: 
          return '';
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch(status) {
        case 0: return '待处理';
        case 1: return '处理中';
        case 2: return '已完成';
        case 3: return '已取消';
        default: return status;
      }
    },
    
    // 导出Excel
    async handleExport() {
      try {
        this.exportLoading = true;
        
        // 定义表头
        const header = [
          { label: '所属小区', prop: 'community' },
          { label: '报修人', prop: 'reporter' },
          { label: '联系方式', prop: 'contact' },
          { label: '报修地址', prop: 'address' },
          { label: '报修内容', prop: 'description' },
          { label: '报修时间', prop: 'reportTime' },
          { label: '处理状态', prop: 'statusText' }
        ];
        
        // 获取所有数据
        const response = await axios.get('/api/repairs/all');
        const data = response.data.map(item => {
          // 处理状态文本
          item.statusText = this.getStatusText(item.status !== undefined ? item.statusValue : item.status);
          return item;
        });
        
        // 导出Excel
        ExcelUtil.exportExcel(data, '报修信息表', header);
        
        ElMessage.success('导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败: ' + (error.message || '未知错误'));
      } finally {
        this.exportLoading = false;
      }
    },
    
    // 打开导入对话框
    handleImport() {
      this.importDialogVisible = true;
      this.fileList = [];
    },
    
    // 下载导入模板
    async downloadTemplate() {
      try {
        // 创建模板数据
        const templateData = [
          {
            community: '阳光花园',
            reporter: '张三',
            contact: '13800138000',
            address: '1栋1单元101',
            description: '水管漏水',
            reportTime: '2023-05-15 10:30:00',
            statusText: '待处理'
          }
        ];
        
        // 定义表头
        const header = [
          { label: '所属小区', prop: 'community' },
          { label: '报修人', prop: 'reporter' },
          { label: '联系方式', prop: 'contact' },
          { label: '报修地址', prop: 'address' },
          { label: '报修内容', prop: 'description' },
          { label: '报修时间', prop: 'reportTime' },
          { label: '处理状态', prop: 'statusText' }
        ];
        
        // 导出模板
        ExcelUtil.exportExcel(templateData, '报修信息导入模板', header);
        
        ElMessage.success('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        ElMessage.error('下载模板失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 文件选择变更
    handleFileChange(file) {
      this.fileList = [file];
    },
    
    // 提交导入
    async submitImport() {
      if (!this.fileList.length) {
        ElMessage.warning('请选择要导入的Excel文件');
        return;
      }
      
      try {
        this.importing = true;
        
        // 读取Excel文件
        const file = this.fileList[0].raw;
        
        // 定义表头映射
        const header = [
          { label: '所属小区', prop: 'community' },
          { label: '报修人', prop: 'reporter' },
          { label: '联系方式', prop: 'contact' },
          { label: '报修地址', prop: 'address' },
          { label: '报修内容', prop: 'description' },
          { label: '报修时间', prop: 'reportTime' },
          { label: '处理状态', prop: 'statusText' }
        ];
        
        // 解析Excel数据
        const importedData = await ExcelUtil.importExcel(file, header);
        
        // 处理导入数据，转换状态文本为状态值
        const processedData = importedData.map(item => {
          // 处理状态值
          switch(item.statusText) {
            case '待处理': item.status = 0; break;
            case '处理中': item.status = 1; break;
            case '已完成': item.status = 2; break;
            case '已取消': item.status = 3; break;
            default: item.status = 0;
          }
          
          // 查找小区ID
          const community = this.communities.find(c => c.name === item.community);
          if (community) {
            item.communityId = community.id;
          }
          
          return item;
        });
        
        // 提交到后端
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await axios.post('/api/repairs/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        ElMessage.success(`导入成功，成功导入${response.data.successCount || importedData.length}条数据`);
        this.importDialogVisible = false;
        this.fetchRepairs(); // 刷新列表
      } catch (error) {
        console.error('导入失败:', error);
        ElMessage.error('导入失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      } finally {
        this.importing = false;
      }
    },
    
    // 添加报修
    handleAdd() {
      this.$router.push('/property/service/repair/add');
    },
    
    // 编辑报修
    handleEdit(row) {
      this.$router.push({
        path: '/property/service/repair/add',
        query: { id: row.id }
      });
    },
    
    // 删除报修
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm(`确认要删除此报修记录吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await axios.delete(`/api/repairs/${row.id}`);
        ElMessage.success('删除成功');
        this.fetchRepairs();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        }
      }
    },
    
    // 批量删除
    async handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }
      
      try {
        await ElMessageBox.confirm(`确认要删除选中的 ${this.multipleSelection.length} 条记录吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const deleteRequests = this.multipleSelection.map(item => 
          axios.delete(`/api/repairs/${item.id}`)
        );
        
        await Promise.all(deleteRequests);
        ElMessage.success('批量删除成功');
        this.fetchRepairs();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error);
          ElMessage.error('批量删除失败');
        }
      }
    },
    
    // 选择变更
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    // 页码变更
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchRepairs();
    },
    
    // 页数变更
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchRepairs();
    }
  }
};
</script>

<style scoped>
.repair-list-container {
  padding: 10px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-select .el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.cell-with-icon .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

/* 分页样式 */
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-box :deep(.el-pagination) {
  font-size: 16px;
}

.pagination-box :deep(.el-pagination .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

.pagination-box :deep(.el-pagination button) {
  font-size: 16px;
  min-width: 36px;
  height: 36px;
}

/* 按钮样式调整 */
:deep(.el-button--text) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 2px 8px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

/* 导入导出相关样式 */
.import-dialog-content {
  padding: 10px 0;
}

.template-download {
  margin-bottom: 20px;
  text-align: center;
}

.excel-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}
</style> 